<?php
$pageTitle = '报名';
require_once 'header.php';

// 获取ID
if (!isset($_GET['id'])) {
    header('Location: index.php');
    exit;
}

$trainingId = $_GET['id'];
$data = array();

if (isset($_SESSION['school'])) {
    $school = $_SESSION['school'];

    if ($school == '') {
        header('Location: index.php');
        exit;
    }

    // 查询培训信息
    $stmt = $pdo->prepare('SELECT department, id, title, start_time, end_time, location, type FROM trainings WHERE id = ?');
    if ($stmt->execute([$trainingId])) {
        $data['training'] = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        die('查询培训失败: ' . $stmt->errorInfo()[2]);
    }

    // 查询学校所有教师 查询已报名的教师
    if ($_SESSION['username'] == 'admin') {
        $stmt = $pdo->prepare('SELECT id, school, name, subject, phone FROM teachers ORDER BY name ASC');
        if ($stmt->execute()) {
            $data['teachers'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            die('查询教师失败: ' . $stmt->errorInfo()[2]);
        }
        $stmt = $pdo->prepare('SELECT teacher_id FROM trainings_teachers WHERE training_id = ?');
        if ($stmt->execute([$trainingId])) {
            $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $data['checkedTeacherIds'] = array_column($teachers, 'teacher_id');
            echo '<script>console.log(' . json_encode($data['checkedTeacherIds']) . ');</script>';
        }
    } else {
        $stmt = $pdo->prepare('SELECT id, school, name, subject, phone FROM teachers WHERE school = ? ORDER BY name ASC');
        if ($stmt->execute([$school])) {
            $data['teachers'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            die('查询教师失败: ' . $stmt->errorInfo()[2]);
        }
        $stmt = $pdo->prepare('SELECT teacher_id FROM trainings_teachers WHERE training_id = ? AND teacher_school = ?');
        if ($stmt->execute([$trainingId, $school])) {
            $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $data['checkedTeacherIds'] = array_column($teachers, 'teacher_id');
            echo '<script>console.log(' . json_encode($data['checkedTeacherIds']) . ');</script>';
        }
    }
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <h1 class="mt-4">培训报名</h1>
            <table class="table table-bordered table-striped">
                <tr>
                    <th>ID</th>
                    <th>主办科室或学校</th>
                    <th>培训主题</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>地点</th>
                    <th>任务或自主</th>
                </tr>
                <tr>
                    <td><?= $data['training']['id'] ?></td>
                    <td><?= $data['training']['department'] ?></td>
                    <td><?= $data['training']['title'] ?></td>
                    <td><?= $data['training']['start_time'] ?></td>
                    <td><?= $data['training']['end_time'] ?></td>
                    <td><?= $data['training']['location'] ?></td>
                    <td><?= $data['training']['type'] ?></td>
                </tr>
            </table>
            <div class="d-flex justify-content-between mb-3">
                <button class="btn btn-success" onclick="batchRegister()">批量报名</button>
                <small>点选复选框，然后点批量报名。</small>
            </div>

            <div class="table-responsive">
                <table id="teachersTable" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all"></th>
                            <th>ID</th>
                            <th>学校</th>
                            <th>姓名</th>
                            <th>科目</th>
                            <th>联系电话</th>
                        </tr>
                    </thead>
                    <tbody id="teacherTable">
                        <?php foreach ($data['teachers'] as $teacher): ?>
                            <tr>
                                <td><input type="checkbox" value="<?= $teacher['id'] ?>" <?= in_array($teacher['id'], $data['checkedTeacherIds']) ? 'checked' : '' ?>></td>
                                <td><?= $teacher['id'] ?></td>
                                <td><?= $teacher['school'] ?></td>
                                <td><?= $teacher['name'] ?></td>
                                <td><?= $teacher['subject'] ?></td>
                                <td><?= $teacher['phone'] ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>

<script>
    // js/training_registration.js - 培训报名页面交互逻辑
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded');

        const teacherTable = document.getElementById('teacherTable');
        const selectAllCheckbox = document.getElementById('select-all');
        const trainingId = <?= $trainingId ?>;

        // 获取所有选中的教师ID
        function getSelectedTeacherIds() {
            const checkboxes = teacherTable.querySelectorAll('input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => parseInt(cb.value));
        }

        // 批量报名
        function batchRegister() {
            const selectedIds = getSelectedTeacherIds();
            /*
            if (selectedIds.length === 0) {
                alert('请至少选择一位教师进行报名');
                return;
            }
            */

            if (!confirm(`确定要为选中的${selectedIds.length}位教师报名？`)) {
                return;
            }

            fetch('teacher_training_registration_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        action: 'batch_register',
                        training_id: trainingId,
                        teacherIds: selectedIds
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert('批量报名成功');
                    } else {
                        alert('批量报名失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('请求错误:', error);
                    alert('发生错误，请查看控制台日志');
                });
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const checkboxes = teacherTable.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(cb => cb.checked = selectAllCheckbox.checked);
        }

        // 事件监听器
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', toggleSelectAll);
        }

        window.batchRegister = batchRegister;
    });
</script>